import struct
import socket
from time import sleep
from pickle import loads

# Connect to the tracker.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock.connect(('', 23456))

# Send registration.
request = struct.pack("!16s40sH", "REGISTER", "foo", 34666) 
sock.send(request)
answer = sock.recv(1024)
print answer

# Try to re-register.
sleep(0.5)
sock.send(request)
answer = sock.recv(1024)
print answer

# Update your activity.
request = struct.pack("!16s40sH", "UPDATE", "foo", 34666)
for x in range(0, 5):
    sock.send(request)
    answer = sock.recv(1024)
    print answer    
    sleep(0.2)

# Get some peers.
request = struct.pack("!16s40sH", "PEER REQUEST", "foo", 34666)
sock.send(request)
answer = sock.recv(1024)
try:
    peers = loads(answer)
    for peer in peers:
        print peer
except:
    print answer

# Leave the brook.
request = struct.pack("!16s40sH", "LEAVE", "foo", 34666)
sock.send(request)
answer = sock.recv(1024)
print answer

# Get some peers again.
request = struct.pack("!16s40sH", "PEER REQUEST", "foo", 34666)
sock.send(request)
answer = sock.recv(1024)
try:
    peers = loads(answer)
    for peer in peers:
        print peer.addr
except:
    print answer
    
sock.close()

